package org.xx.armory.web.tags;

import org.apache.commons.io.IOUtils;

import javax.servlet.jsp.JspException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

public final class AScript extends BaseTagHandler {
    private static final long serialVersionUID = 1L;
    private static final Charset DEFAULT_CHARSET;
    private static final String SCRIPT_PATH = "js";
    private static final String IMAGES_PATH = "images";
    private static final String DEFAULT_PROPOSAL = "default";

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
    }

    private String proposal = "default";

    public AScript() {
    }

    public final String getPro() {
        return this.proposal;
    }

    public final void setPro(String value) {
        this.proposal = value == null ? DEFAULT_PROPOSAL : value.trim();
    }

    public int doStartTag()
            throws JspException {
        super.doStartTag();
        this.getRenderer().comment("Scripts goes here");
        String profile = TagUtils.evalThemeUrl(this.pageContext, SCRIPT_PATH, this.getPro() + ".txt");

        final List<String> lines;
        try (final InputStream ins = this.getStaticResourceAsStream(profile)) {
            lines = IOUtils.readLines(ins, DEFAULT_CHARSET);
        } catch (IOException ex) {
            throw new JspException(ex);
        }

        for (final String line : lines) {
            if (line != null && !line.isEmpty()) {
                this.getRenderer().newline();
                this.getRenderer().setAttribute("type", "text/javascript");
                this.getRenderer().setAttribute("src", TagUtils.evalRelThemeUrl(this.pageContext, SCRIPT_PATH, line));
                this.getRenderer().startTag("script", false);
                this.getRenderer().endTag();
            }
        }

        String relRootUrl = TagUtils.evalRelUrl(this.pageContext, "/");
        final String line = TagUtils.evalRelThemeUrl(this.pageContext, IMAGES_PATH);
        this.getRenderer().newline();
        this.getRenderer().setAttribute("type", "text/javascript");
        this.getRenderer().startTag("script", false);
        this.getRenderer().newline();
        this.getRenderer().writeRaw("Sys.setRootUrl('" + relRootUrl + "');\n");
        this.getRenderer().writeRaw("Sys.setImageUrl('" + line + "');\n");
        Date now = new Date();
        this.getRenderer().writeRaw("var serverTime = function() { var r = new Date(); r.setTime(" + now.getTime() + "); return r; };\n");
        this.getRenderer().endTag();
        return 0;
    }
}

